package com.dhcc.bpm.common.utils;

import org.apache.maven.shared.invoker.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Collections;

/**
 * @program: cbus-bpm-boot
 * @ClassName MavenUtils
 * @description: TODO
 * @author: xiafayu
 * @create: 2021-12-15 14:11:39
 * @Version 1.0
 **/
@Component
public class MavenInvokerUtils {
    private static final Logger log = LoggerFactory.getLogger(MavenInvokerUtils.class);

    @Value("${bpm.mvn-home}")
    private String mvnHome;
    @Value("${bpm.mvn-log-enable}")
    private boolean logEnable;

    public boolean createSdkJar(String pomPath) {
        log.info("pom文件路径：{}", pomPath);
        InvocationRequest request = new DefaultInvocationRequest();
        request.setPomFile(new File(pomPath));
        request.setGoals(Collections.singletonList("clean package"));

        Invoker invoker = new DefaultInvoker();
        invoker.setMavenHome(new File(mvnHome));

        if(logEnable){
            invoker.setLogger(new PrintStreamLogger(System.err, InvokerLogger.ERROR) {});

            invoker.setOutputHandler(new InvocationOutputHandler() {
                @Override
                public void consumeLine(String line) throws IOException {
                    log.info(line);
                }
            });
        }


        try {
            invoker.execute(request);
        } catch (MavenInvocationException e) {
            log.error("执行异常：{}", e);
        }


        try {
            if (invoker.execute(request).getExitCode() == 0) {
                log.info("执行成功！");
                return true;
            } else {
                log.info("执行失败！");
                return false;
            }
        } catch (MavenInvocationException e) {
            log.error("执行异常：{}", e);
        }
        return false;
    }
}
